package com.examples.demo;


import okhttp3.*;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.util.Collector;

@SuppressWarnings("deprecation")
public class JDkveder {



    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> lineDS = env.readTextFile("E:\\temp\\data2\\data1\\5526122--20230302all.txt");
        lineDS.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String sss =  tanss(s);
                collector.collect(sss);
            }
        }).setParallelism(4).addSink(new SinkFunction<String>() {
            @Override
            public void invoke(String value, Context context) throws Exception {
                SinkFunction.super.invoke(value, context);
                System.out.println("value = " + value);
            }
        });
        env.execute();


    }

    private static String tanss(String s) {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "srcLang=zh&tgtLang=vi&method=translate&useSocket=true&text="+s);
            Request request = new Request.Builder()
                    .url("http://219.159.152.7:19998/NatureAPI/openapi.do")
                    .method("POST", body)
                    .addHeader("User-Agent", "PostmanRuntime/7.34.0")
                    .addHeader("Accept", "*/*")
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Postman-Token", "6acb282b-f970-40f8-85a1-07e9d95ae7e1")
                    .addHeader("Host", "219.159.152.7:19998")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
            System.out.println("response = " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
